<!DOCTYPE html>
<!--suppress JSUnresolvedFunction -->
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.thymeleaf.org"
      layout:decorate="~{manage/layout}" lang="zh">
<head>
    <title>添加文章</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/simplemde/1.11.2/simplemde.min.css"/>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/simplemde/1.11.2/simplemde.min.js"></script>

    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

    <style rel="stylesheet">
        .main-container {
            height: calc(100% - 16px);
        }

        #form {
            height: 100%;
        }

        .editormd-preview-container, .editormd-html-preview {
            overflow-y: hidden;
        }

        .mdc-card__action-buttons > a, .mdc-card__action-buttons > button {
            max-width: 64px;
        }

        .mdc-card__action-buttons > button {
            right: 0;
        }

        #markdown-editor {
            z-index: 6;
        }
    </style>
</head>
<body>
<div layout:fragment="main-container" class="main-container">
    <form id="form" class="mdc-card mdc-card__non-shadow" onsubmit="void(0);">
        <input th:if="${_csrf!=null}" type="hidden"
               th:name="${_csrf.parameterName}"
               id="_csrf"
               th:value="${_csrf.token}"/>
        <h2 class="mdc-typography mdc-typography--headline5 mdc-text__align-center">
            [[${article ne null?'修改':'添加'}]]文章
        </h2>
        <!--标题-->
        <!--<div class="text-field-container mdc-panel__margin-16">-->
        <!--    <div class="mdc-text-field mdc-text-field&#45;&#45;outlined mdc-text-field-row"-->
        <!--         data-mdc-auto-init="MDCTextField">-->
        <!--        <input type="text" id="titleInput" name="title"-->
        <!--               class="mdc-text-field__input"-->
        <!--               maxlength="50"-->
        <!--               required-->
        <!--               data-validtip="标题不能为空,且小于20个字符"-->
        <!--               autocomplete="off"-->
        <!--               placeholder="请输入文章标题"-->
        <!--               th:value="${article ne null?article.title:''}">-->
        <!--        <div class="mdc-notched-outline">-->
        <!--            <div class="mdc-notched-outline__leading"></div>-->
        <!--            <div class="mdc-notched-outline__notch">-->
        <!--                <label for="titleInput" class="mdc-floating-label">标题</label>-->
        <!--            </div>-->
        <!--            <div class="mdc-notched-outline__trailing"></div>-->
        <!--        </div>-->
        <!--    </div>-->
        <!--    <div class="mdc-text-field-helper-line">-->
        <!--        <p class="mdc-text-field-helper-text mdc-text-field-helper-text&#45;&#45;persistent mdc-text-field-helper-text&#45;&#45;validation-msg">-->
        <!--            *必填</p>-->
        <!--        <div class="mdc-text-field-character-counter">0 / 50</div>-->
        <!--    </div>-->
        <!--</div>-->
        <!--概述-->
        <!--<div class="text-field-container mdc-panel__margin-16">-->
        <!--    <div class="mdc-text-field mdc-text-field&#45;&#45;outlined mdc-text-field-row"-->
        <!--         data-mdc-auto-init="MDCTextField">-->
        <!--        <input type="text" id="descInput" name="description"-->
        <!--               class="mdc-text-field__input"-->
        <!--               maxlength="250"-->
        <!--               required-->
        <!--               data-validtip="概述不能为空,且小于20个字符"-->
        <!--               autocomplete="off"-->
        <!--               placeholder="请输入文章标题"-->
        <!--               th:value="${article ne null?article.description:''}">-->
        <!--        <div class="mdc-notched-outline">-->
        <!--            <div class="mdc-notched-outline__leading"></div>-->
        <!--            <div class="mdc-notched-outline__notch">-->
        <!--                <label for="descInput" class="mdc-floating-label">概述</label>-->
        <!--            </div>-->
        <!--            <div class="mdc-notched-outline__trailing"></div>-->
        <!--        </div>-->
        <!--    </div>-->
        <!--    <div class="mdc-text-field-helper-line">-->
        <!--        <p class="mdc-text-field-helper-text mdc-text-field-helper-text&#45;&#45;persistent mdc-text-field-helper-text&#45;&#45;validation-msg">-->
        <!--            *必填</p>-->
        <!--        <div class="mdc-text-field-character-counter">0 / 250</div>-->
        <!--    </div>-->
        <!--</div>-->
        <!--标签-->
        <div class="text-field-container mdc-panel__margin-16">
            <div class="mdc-text-field mdc-text-field--outlined mdc-text-field-row"
                 data-mdc-auto-init="MDCTextField">
                <input type="text" id="tagIdsInput" name="tagIds"
                       class="mdc-text-field__input"
                       maxlength="50"
                       data-validtip="标签不能为空,且小于20个字符"
                       autocomplete="off"
                       placeholder="请输入文章标签">
                <div class="mdc-notched-outline">
                    <div class="mdc-notched-outline__leading"></div>
                    <div class="mdc-notched-outline__notch">
                        <label for="tagIdsInput" class="mdc-floating-label"></label>
                    </div>
                    <div class="mdc-notched-outline__trailing"></div>
                </div>
            </div>
            <div class="mdc-text-field-helper-line">
                <p class="mdc-text-field-helper-text mdc-text-field-helper-text--persistent mdc-text-field-helper-text--validation-msg">
                    *必填</p>
            </div>
        </div>
        <!-- markdown内容 -->
        <div class="" id="markdown-editor">
            <textarea id="content" th:text="${article ne null ? article.content : ''}"></textarea>
        </div>
        <!--操作-->
        <div class="mdc-layout-grid__inner mdc-card__action-buttons mdc-layout-grid--align-right mdc-container__relative">
            <div class="mdc-layout-grid__cell "></div>
            <a href="/manage/article/index"
               class="mdc-button mdc-layout-grid__cell mdc-card__action mdc-button--raised mdc-ripple-upgraded">
                返回
            </a>
            <button id="editBtn"
                    class="mdc-button mdc-layout-grid__cell mdc-button--raised mdc-ripple-upgraded mdc-container__absolute"
                    th:inline="text">
                [[${article eq null ? '添加':'更新'}]]
            </button>
        </div>
    </form>
</div>
<div layout:fragment="script">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/tagify/3.17.1/tagify.min.css"/>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/tagify/3.17.0/tagify.min.js"></script>
    <script type="text/javascript" th:inline="javascript">
      $(function() {
        let id = [[${article ne null ? article.id : ''}]];
        let tagify = new Tagify($('input[name=tagIds]')[0]);
        let existTags = [[${article ne null ? article.tags : null}]];
        if (existTags) {
          // 回显标签
          tagify.addTags(existTags.map(o => {
            return {
              'value': o.name,
              'id': o.id,
            };
          }));
        }
        // 初始化 markdown 编辑器
        let simplemde = new SimpleMDE({element: $('#content')[0], autoDownloadFontAwesome: false});
        // 标签输入
        let controller;
        let autoCompleteTag = function(e) {
          let value = e.detail.value;
          // reset the whitelist
          tagify.settings.whitelist.length = 0;
          // https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort
          controller && controller.abort();
          controller = new AbortController();

          // show loading animation and hide the suggestions dropdown
          tagify.loading(true).dropdown.hide.call(tagify);
          fetch('/manage/tag/page?criteria=' + value, {signal: controller.signal}).
              then(RES => RES.json()).
              then(function(res) {
                let whitelist = res.data.content.map(o => {
                  return {'value': o.name, 'id': o.id};
                });
                // update inwhitelist Array in-place
                tagify.settings.whitelist.splice(0, whitelist.length, ...whitelist);
                tagify.loading(false).dropdown.show.call(tagify, value); // render the suggestions dropdown
              });
        };
        tagify.on('input', autoCompleteTag);
        // 提交表单
        $('#editBtn').on('click', function() {
          let data = {};
          let content = simplemde.value();
          if (!$.trim(content)) {
            $.alert('文章内容 不能为空');
            return false;
          }
          // let title = $('#titleInput').val();
          // markdown第一行[# ]后的内容视为标题
          let title = content.substring(2, content.indexOf('\n')) + ']';
          if (!$.trim(title)) {
            $.alert('文章标题 不能为空');
            return false;
          }
          let description = $('#descInput').val();
          if (!$.trim(description)) {
            $.alert('概述 不能为空');
            return false;
          }
          data.title = title;
          data.content = content;
          data.description = description;
          // 新增标签
          let tags = $('input[name=tagIds]').val();
          console.debug(tags);
          if (tags && tags.length > 0) {
            tags = JSON.parse(tags);
            data.tagIds = tags.map(o => o.id).filter(o => o);
            // 如果没有id,需要新增,处理成标准格式
            let newTags = tags.filter(o => !(o.id)).map(o => {
              return {'name': o.value};
            });
            if (!newTags || newTags.length === 0) {
              submitForm(data);
              return false;
            }
            // 需要新增标签
            $.ajax({
              url: '/manage/tag/batch',
              method: 'POST',
              data: JSON.stringify(newTags),
              contentType: 'application/json',
              success: function(res) {
                if (!res.result) {
                  $.alert(res.msg);
                  return false;
                }
                console.debug(res);
                res.data.forEach(o => data.tagIds.push(o));
                submitForm(data);
              },
            });
            return false;
          } else {
            $.alert('标签 不能为空');
            return false;
          }
        });

        function submitForm(data) {
          data.tagIds = data.tagIds.toString();
          console.log(JSON.stringify(data));
          id > 0 ?
              $.put('/manage/article/' + id, data, function(res) {
                res.result === true ? $.alert(res.msg, function() {
                  window.location.href = '/manage/article/index';
                }) : $.alert(res.msg);
              }) : $.post('/manage/article', data, function(res) {
                res.result === true ? $.alert(res.msg, function() {
                  window.location.href = '/manage/article/index';
                }) : $.alert(res.msg);
              });
        }
      });
    </script>
</div>
</body>
</html>
